import math
from torch.utils.data import Dataset, DataLoader, random_split
from torch import Tensor, nn, optim
import torch
import random

class ExampleDataset(Dataset):

    # 通过正弦函数和随机噪声，构造周期为T、输入尺寸是input_size、样本数是sample_total的时间序列数据集
    # 大致是这样的：
    # 模型输入        | 模型输出
    # ?, ?, ?, ...   | ?
    # ?, ?, ?, ...   | ?
    # ?, ?, ?, ...   | ?
    # 作为模型输入的列表元素数量是input_size，模型输出的列表元素数量硬编码为1
    # 假设时间序列是：1, 2, 3, 4, 5, 6, ...，input_size是4，那么数据格式是：
    # 模型输入 | 模型输出
    # 1, 2, 3, 4 | 5
    # 2, 3, 4, 5 | 6
    # ...
    def __init__(self, T = 50, input_size = 100, sample_total = 1000):
        self.time_series = []
        for i in range(sample_total + input_size):
            x = i
            y = math.sin(2 * math.pi * 1 / T * x) + random.normalvariate(0, 0.02)
            self.time_series.append([y])
        self.input_size = input_size
        self.sample_total = sample_total

    def __len__(self):
        return self.sample_total

    def __getitem__(self, idx):
        network_input = self.time_series[idx:(idx + self.input_size)]
        network_output = self.time_series[idx + self.input_size]
        return Tensor(network_input), Tensor(network_output)

class NeuralNetwork(nn.Module):

    def __init__(self, input_item_size = 1, output_item_size = 1):
        super().__init__()
        self.input_item_size = input_item_size
        self.output_item_size = output_item_size

        # LSTM Layer:
        num_layers = 3

        self.lstm = nn.LSTM(input_item_size, output_item_size, num_layers, batch_first=True)
        self.linear = nn.Linear(output_item_size, output_item_size)

    def forward(self, input_data):
        lstm_out, _ = self.lstm(input_data)
        return self.linear(lstm_out[:, -1, :])

def show_dataset():
    batch_size = 1
    dataset_object = DatasetLSTMForLearningPurposes(30, 7, 100)
    data_loader = DataLoader(dataset_object, batch_size=batch_size)
    for x, y in data_loader:
        print('x=')
        print(x[0])
        print('y=')
        print(y[0])
        break

def train(dataloader, model, loss_fn, optimizer):
    size = len(dataloader.dataset)
    model.train()
    for batch, (X, y) in enumerate(dataloader):
        pred = model(X)
        loss = loss_fn(pred, y)

        loss.backward()
        optimizer.step()
        optimizer.zero_grad()

        if batch % 6 == 0 or (batch) * dataloader.batch_size + len(X) == size:
            loss, current = loss.item(), (batch) * dataloader.batch_size + len(X)
            print(f"loss: {loss:>7f}  [{current:>5d}/{size:>5d}]")

def test(dataloader, model, loss_fn):
    model.eval()
    size = len(dataloader.dataset)
    num_batches = len(dataloader)
    test_loss = 0
    with torch.no_grad():
        for X, y in dataloader:
            pred = model(X)
            test_loss += loss_fn(pred, y).item()
    test_loss /= num_batches
    print(f"Test Avg loss: {test_loss:>8f} \n")

def run_train():
    train_data_size = 800
    test_data_size = 200
    dataset_object = ExampleDataset(30, 30, train_data_size + test_data_size)
    train_data, test_data = random_split(dataset_object, [train_data_size, test_data_size])

    batch_size = 100
    train_data_loader = DataLoader(train_data, batch_size=batch_size)
    test_data_loader = DataLoader(test_data, batch_size=batch_size)

    model = NeuralNetwork()
    loss_fn = nn.MSELoss()
    optimizer = optim.Adam(model.parameters(), lr=0.001)

    epochs = 4000
    for t in range(epochs):
        print(f"Epoch {t+1}\n-------------------------------")
        train(train_data_loader, model, loss_fn, optimizer)
        test(test_data_loader, model, loss_fn)
    print("Done!")

    # 下面的代码用来根据测试集的一个样本接着循环预测后面，不需要可以return退出
    # return
    model.eval()
    output_series = []
    with torch.no_grad():
        # 使用测试集最后一个样本输入
        for x, y in test_data_loader:
            out = model(Tensor(x[-1]).view(1, -1, len(x[-1][-1])))
            break
        for i in range(len(x[-1][1:])):
            output_series.append(x[-1][i + 1].item())
        output_series.append(out[-1][-1].item())

        for _ in range(100):
            input_data = Tensor(output_series).view(1, -1, 1)
            out = model(input_data)
            output_series.append(out[-1][-1].item())
    with open('test.csv', 'w') as fp:
        fp.write("时间序列\n")
        for o in output_series:
            fp.write(str(o) + "\n")

if __name__ == '__main__':
    run_train()
